package rpc

import (
	"encoding/json"
	"fmt"
	"bytes"
	"io/ioutil"
	"log"
	"net/http"
	"errors"
)

const BlockChainURL = "http://139.220.193.149:7999"
//const BlockChainURL = "http://10.103.244.217:7999/"
const ManageCenterHost = "http://211.159.157.176:10000/manage/business/active"

type BindSignInfo struct {
	WalletId  string  `json:"walletId"`
	ActivationCode string  `json:"activationCode"`
	PeerId string `json:"peerId"`
}
func SetEthHost()(string){
	return BlockChainURL
}
func SetManageCenterHost()(string){
	return ManageCenterHost
}
func HttpEthPost( rpc RPCParam ,sendethHost string)(interface{}, error) {
	b, err := json.Marshal(rpc)
	if err != nil {
		return "", err
	}
	body := bytes.NewBuffer([]byte(b))
	res,err := http.Post(sendethHost, "application/json;charset=utf-8", body)
	if err !=nil{
		return "", err
	}
	result, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		return "", err
	}
	var s RPCResult;
	err = json.Unmarshal(result, &s)
	if s.Error.Code!=0 {
		return "", errors.New(s.Error.Message)
	}
	return s.Result, nil
}
func SendSignInfoToManagementCenter(address string, regcode string, peerID string)(int, string, error){
	var Binddata BindSignInfo
	Binddata.WalletId = address
	Binddata.ActivationCode = regcode
	Binddata.PeerId = peerID
	BindJson,err := json.Marshal(Binddata)
	if err != nil {
		fmt.Println("json err:", err)
	}
	body := bytes.NewBuffer([]byte(BindJson))
	res,err := http.Post(SetManageCenterHost(), "application/json;charset=utf-8", body)
	if err != nil {
		log.Fatal(err)
	}
	var Result struct {
		Result int   `json:"result"`
		Message string `json:"message"`
	}
	result, err := ioutil.ReadAll(res.Body)
	defer res.Body.Close()
	if err != nil {
		return 0,"", err
	}
	err2 := json.Unmarshal(result,&Result)
	if err2 != nil {
		return 0,"", err
	}
	if Result.Result == 0 {
		fmt.Printf("active fail! %s\n", Result.Message)//message: 激活失败
	}
	if Result.Result == 1 {
		fmt.Printf("active success! %s\n", Result.Message)//message: 激活成功
	}
	return  Result.Result, Result.Message, nil
}